package com.infinit.selfhelp.common.loading

import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.view.Gravity
import android.view.WindowManager
import android.widget.ImageView
import com.infinit.selfhelp.common.R
import com.infinit.selfhelp.common.ext.loadGif

class ClickableLoadingDelegate : ILoadingDelegate {

    private var dialog: Dialog? = null

    override fun showDialog(context: Context, cancelable: Boolean, cancelListener: DialogInterface.OnCancelListener?) {
        return showDialog(context, null, cancelable, cancelListener)
    }

    override fun showDialog(context: Context, message: CharSequence?, cancelable: Boolean, cancelListener: DialogInterface.OnCancelListener?) {
        if (dialog == null) {
            dialog = Dialog(context, R.style.LoadingDialog)
            dialog?.setContentView(R.layout.view_loading_dialog)
            loadGifByGlide()
            dialog?.setCanceledOnTouchOutside(false)
            dialog?.setCancelable(cancelable)
            dialog?.setOnCancelListener(cancelListener)
            dialog?.window?.attributes?.gravity = Gravity.CENTER
            val params = dialog?.window?.attributes
            params?.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND or WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
            params?.dimAmount = 0.2f
            dialog?.window?.attributes = params
            dialog?.show()
        } else if (dialog?.isShowing == false) {
            dialog?.show()
        }
    }

    override fun dismissDialog() {
        if (dialog != null && dialog?.isShowing == true) {
            dialog?.dismiss()
        }
    }

    private fun loadGifByGlide() {
        val ivLoadingGif = dialog?.findViewById<ImageView>(R.id.loadingGif)
        ivLoadingGif?.loadGif(R.drawable.loading)
    }
}
